import { useState, useEffect } from 'react';
import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { stripeService } from '../services/stripe';
import { useLanguage } from '@kernelproxy/i18n';
import { useToast } from '../contexts/ToastContext';

interface StripePaymentFormProps {
  clientSecret: string;
  amount: number;
  onSuccess: () => void;
  onCancel: () => void;
}

const StripePaymentForm = ({ clientSecret, amount, onSuccess, onCancel }: StripePaymentFormProps) => {
  const stripe = useStripe();
  const elements = useElements();
  const { language } = useLanguage();
  const toast = useToast();
  const [isProcessing, setIsProcessing] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsProcessing(true);

    try {
      const result = await stripeService.confirmPayment(
        stripe,
        elements,
        clientSecret
      );

      if (result.success) {
        toast.success(language === 'zh-CN' ? '支付成功！' : 'Payment successful!');
        onSuccess();
      } else {
        const errorMsg = typeof result.error === 'string' ? result.error : (language === 'zh-CN' ? '支付失败，请重试' : 'Payment failed, please try again');
        toast.error(errorMsg);
      }
    } catch (error) {
      console.error('Payment error:', error);
      toast.error(language === 'zh-CN' ? '支付处理失败' : 'Payment processing failed');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="mb-4">
        <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
          {language === 'zh-CN' ? '支付金额：' : 'Amount: '}
          <span className="font-bold text-lg text-gray-900 dark:text-white">
            ${amount.toFixed(2)}
          </span>
        </p>
      </div>

      <div className="border border-gray-300 dark:border-gray-600 rounded-lg p-4 bg-white dark:bg-gray-800">
        <PaymentElement 
          options={{
            layout: 'tabs',
            paymentMethodOrder: ['card', 'wechat_pay', 'alipay', 'customer_balance', 'us_bank_account'],
          }}
        />
      </div>

      <div className="flex space-x-3 mt-6">
        <button
          type="button"
          onClick={onCancel}
          disabled={isProcessing}
          className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {language === 'zh-CN' ? '取消' : 'Cancel'}
        </button>
        <button
          type="submit"
          disabled={isProcessing || !stripe || !elements}
          className="flex-1 px-4 py-2 bg-gradient-to-r from-[#00d4ff] to-[#0f1c3f] text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isProcessing 
            ? (language === 'zh-CN' ? '处理中...' : 'Processing...') 
            : (language === 'zh-CN' ? `支付 $${amount.toFixed(2)}` : `Pay $${amount.toFixed(2)}`)}
        </button>
      </div>
    </form>
  );
};

interface StripePaymentModalProps {
  isOpen: boolean;
  amount: number;
  onSuccess: () => void;
  onClose: () => void;
}

export const StripePaymentModal = ({ isOpen, amount, onSuccess, onClose }: StripePaymentModalProps) => {
  const { language } = useLanguage();
  const toast = useToast();
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [stripePromise, setStripePromise] = useState<any>(null);
  
  // Detect dark mode
  const isDarkMode = document.documentElement.classList.contains('dark');

  useEffect(() => {
    // Load Stripe
    const loadStripeInstance = async () => {
      const stripe = await stripeService.getStripe();
      setStripePromise(stripe);
    };
    loadStripeInstance();
  }, []);

  useEffect(() => {
    if (isOpen && !clientSecret) {
      createPaymentIntent();
    }
  }, [isOpen]);

  const createPaymentIntent = async () => {
    setIsLoading(true);
    try {
      const result = await stripeService.createPaymentIntent(amount);
      if (result.success && result.clientSecret) {
        setClientSecret(result.clientSecret);
      } else {
        // Show detailed error message
        const errorMsg = result.error instanceof Error 
          ? result.error.message 
          : (typeof result.error === 'string' ? result.error : (language === 'zh-CN' ? '创建支付会话失败' : 'Failed to create payment session'));
        console.error('Payment intent creation failed:', result.error);
        toast.error(errorMsg);
        onClose();
      }
    } catch (error) {
      console.error('Failed to create payment intent:', error);
      const errorMsg = error instanceof Error 
        ? error.message 
        : (language === 'zh-CN' ? '创建支付会话失败' : 'Failed to create payment session');
      toast.error(errorMsg);
      onClose();
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setClientSecret(null);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full p-6">
        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
          {language === 'zh-CN' ? 'Stripe 安全支付' : 'Stripe Secure Payment'}
        </h3>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#00d4ff]"></div>
          </div>
        ) : clientSecret && stripePromise ? (
          <Elements
            stripe={stripePromise}
            options={{
              clientSecret,
              locale: language === 'zh-CN' ? 'zh' : 'en',
              appearance: {
                theme: isDarkMode ? 'night' : 'stripe',
                variables: {
                  colorPrimary: '#00d4ff',
                  colorBackground: isDarkMode ? '#1f2937' : '#ffffff',
                  colorText: isDarkMode ? '#f3f4f6' : '#1f2937',
                  colorDanger: '#ef4444',
                  fontFamily: 'system-ui, sans-serif',
                  spacingUnit: '4px',
                  borderRadius: '8px',
                },
                rules: {
                  '.Tab': {
                    backgroundColor: isDarkMode ? '#374151' : '#f9fafb',
                    border: `1px solid ${isDarkMode ? '#4b5563' : '#e5e7eb'}`,
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.Tab:hover': {
                    backgroundColor: isDarkMode ? '#4b5563' : '#f3f4f6',
                  },
                  '.Tab--selected': {
                    backgroundColor: isDarkMode ? '#1f2937' : '#ffffff',
                    borderColor: '#00d4ff',
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.TabIcon': {
                    fill: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.TabIcon--selected': {
                    fill: '#00d4ff',
                  },
                  '.Input': {
                    backgroundColor: isDarkMode ? '#374151' : '#ffffff',
                    border: `1px solid ${isDarkMode ? '#4b5563' : '#d1d5db'}`,
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.Input:focus': {
                    borderColor: '#00d4ff',
                    boxShadow: `0 0 0 1px #00d4ff`,
                  },
                  '.Label': {
                    color: isDarkMode ? '#d1d5db' : '#6b7280',
                  },
                  '.Text': {
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.Error': {
                    color: '#ef4444',
                  },
                  // Card brand icons styling for dark mode
                  '.p-CardBrandIcon': {
                    opacity: isDarkMode ? '0.9' : '1',
                    filter: isDarkMode ? 'brightness(1.2) contrast(0.9)' : 'none',
                  },
                  '.p-CardBrandIcon--selected': {
                    opacity: '1',
                    filter: 'none',
                  },
                },
              },
            }}
          >
            <StripePaymentForm
              clientSecret={clientSecret}
              amount={amount}
              onSuccess={onSuccess}
              onCancel={handleClose}
            />
          </Elements>
        ) : (
          <div className="text-center py-12">
            <p className="text-gray-600 dark:text-gray-400">
              {language === 'zh-CN' ? '加载支付表单...' : 'Loading payment form...'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};
